package com.lancoo.klgcourseware.ui.fragment.basicTrain;

import android.util.Log;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;

import com.lancoo.klgcourseware.R;
import com.lancoo.klgcourseware.base.BaseKlgFragment;
import com.lancoo.klgcourseware.ui.activity.KlgBaseTrainActivity;
import com.lancoo.klgcourseware.ui.fragment.pronounceTrain.PronounceBaseFragment;
import com.stkouyu.entity.LgEvaluateObj;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by pengmi on 2019/8/15 18:35
 * Description:基础训练子训练基类
 */
public abstract class BasicTrainBaseFragment extends BaseKlgFragment {

    private static final String TAG = "BasicTrainBaseFragment";
    public static final String KEY_SPELL_ARTICULATION="spellArticulation";
    public static final String KEY_USAGE_TRAIN="usageTrain";
    public static final String KEY_KLGTYPE="klgType";
    public static final String KEY_IS_SCENE="isScene";
    public static final String KEY_ISLASTTRAINMODEL="isLastTrainModel";
    public static final String KEY_ENABLE_TRAIN="enable_train";
    public static final String KEY_IS_ALERT="is_alert";
    public static final String KEY_ISMORE_ENTER="is_more_enter";//是否是从更多进入的

    public static final String TRAINTAG_SPELL="spell";//单词拼读
    public static final String TRAINTAG_PHONETIC="phonetic";//发音训练
    public static final String TRAINTAG_USAGE="read_sentence_fill";//用法训练，读句填空
    public static final String TRAINTAG_SPELL_MEMORY_WRITE="spell_memory_write";//全拼默写
    public static final String TRAINTAG_LISTEN_REPEAT="listen_repeat";//听音复述
    public static final String TRAINTAG_TRANSLATION="translation";//口语翻译
    public static final String TRAINTAG_SPELL_FILL="spell_fill";//填空拼写
    public static final String TRAINTAG_PHONETIC_PHRASE="phonetic_phase";//词组，esp发音训练

//    protected final int QUALITY_SCORE=60;//训练合格分数
    protected final int RESULT_TIME=10;//训练合格分数
    protected final int REPEAT_TIME=3,TRAINRESULT_TIME=2000,MEDIAREPEAT_TIME=3000;//跟读时间3s,作答结果展示2s,音频带读3s

    protected String currentTrainTag=TRAINTAG_SPELL;
    private TimerTask timerTask_progress,timerTask_second,timerTask_mediaProgress;//录音作答计时器,3秒计时器,示范音播放进度计时器
    private Timer timer_progress,timer_second,timer_mediaProgress;//录音作答计时器,秒计时器
    protected int recorderProgress,secondCountTime=RESULT_TIME,resultCountTime,trainCountTime=TRAINRESULT_TIME;
    private boolean isCountTimePause;//秒倒计时是否暂停


    @Override
    public void onClick(View v) {
        super.onClick(v);
//        if(System.currentTimeMillis()-time<500){
//            return;
//        }
//        time=System.currentTimeMillis();
        int id=v.getId();
        if(id== R.id.tv_pass_train){
            giveUpTrain();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        pauseCountTimeTimer();
        pauseSecondTimer();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        destroyCountTimeTimer();
        destroySecondTimer();
        destroyMeidaProgressTimer();
    }

    /**
     * 列表横向滚动
     * @param recyclerView
     * @param position
     * @param totalSize
     * @param forward
     */
    protected void scrollIndex(RecyclerView recyclerView, int position, int totalSize, boolean forward){
        if(forward){
            recyclerView.smoothScrollToPosition(totalSize-position>8?position+8:totalSize);
        }else{
//            recyclerView.smoothScrollToPosition(0);
            recyclerView.scrollToPosition(0);
        }
    }



    /**
     * 当前模式是否能开始训练
     * @return
     */
    protected boolean enableStartTrain(int alertMsgId ){
        if(getActivity() instanceof KlgBaseTrainActivity){
            boolean enableTrain = ((KlgBaseTrainActivity) getActivity()).enableStartTrain(currentTrainTag);
            Log.e("aaaa","能不能自动播放?"+enableTrain);
            if(enableTrain){
                startTrainDialogCountTime(alertMsgId);
            }
            return enableTrain;
        }else {
            return false;
        }
    }

    public void startTrainDialogCountTime(int alertMsgId){
        changeEnableShowPauseTrainDialogState(true);
        if(getActivity() instanceof KlgBaseTrainActivity){
            ((KlgBaseTrainActivity) getActivity()).startTrainCountTime(alertMsgId);
        }
    }

    protected void startSpeechEvaluation(String evaluationContent,String url){
        if(getActivity() instanceof KlgBaseTrainActivity){
            ((KlgBaseTrainActivity) getActivity()).startSpeechEvaluationEngine(evaluationContent,url);
        }
    }

    protected void stopSpeechEvaluation(boolean isCallBack){
        if(getActivity() instanceof KlgBaseTrainActivity){
            ((KlgBaseTrainActivity) getActivity()).stopSpeechEvaluationEngine(isCallBack);
        }
    }

    protected void enterNextTrainModel(){
        if(getActivity() instanceof KlgBaseTrainActivity){
            ((KlgBaseTrainActivity) getActivity()).startNextTrainModel();
        }
    }

    protected void changeEnableShowPauseTrainDialogState(boolean enableShowPauseDialog){
        if(getActivity() instanceof KlgBaseTrainActivity){
            ((KlgBaseTrainActivity) getActivity()).changeEnableShowPauseTrainDialogState(enableShowPauseDialog);
        }
    }

    protected void playDripSoundMusic(){
        if(getActivity() instanceof KlgBaseTrainActivity){
            ((KlgBaseTrainActivity) getActivity()).playDripMusic();
        }
    }

    protected void pauseThreeSecondTimer(){
        if(getActivity() instanceof KlgBaseTrainActivity){
            ((KlgBaseTrainActivity) getActivity()).pauseThreeSecondTimer();
        }
    }

    /**
     * 更新当前模式下的作答结果
     * @param isQuality
     */
    protected void updateTrainResult(boolean isQuality,float grade){
        if(getActivity() instanceof KlgBaseTrainActivity){
            ((KlgBaseTrainActivity) getActivity()).upDateTrainRecordResult(isQuality,grade);
        }
    }


    /**
     * 暂停滴水音效
     */
    protected void pauseDripSoundPlay(){
        if(getActivity() instanceof KlgBaseTrainActivity){
            ((KlgBaseTrainActivity) getActivity()).pauseDripMusicPlay();
        }
    }

    /**
     * 点击不练了调用
     */
    protected void giveUpTrain(){
        Log.e("aaaa",TAG+",giveUpTrain，当前暂停所有训练处理");
        pauseTrainStudy(false);
        enterNextTrainModel();
//        if(getActivity() instanceof KlgBaseTrainActivity){
//            ((KlgBaseTrainActivity) getActivity()).giveUpTrain();
//        }

    }


    /**
     * 滴水声后开始模式训练
     */
    protected void startTrain(){}

    protected void upDateRecordProgress(){}

    protected void onSuccessSpeechEvaluation(int grade, String url, LgEvaluateObj skegnResult){}

    protected void upDateSecondCountTime(){}

    protected void upDateResultCountTime(int progress,int totalProgress){}

    protected void startNextUsageQuesTrain(){}

    /**
     * 继续训练
     */
    protected void continueTrain(){}

    /**
     * 中止当前的训练
     */
    protected void pauseCurrentSubTrain(boolean isReset){}

    protected void changePronounceSubTrainModel(PronounceBaseFragment.PronounceState pronounceState){}

    protected void changePronounceRepeatTrainModel(int score,String recordUrl){}

    protected void quesResultMuiscPlayer(boolean isCorrect){}

    protected void resetUsageTrain(){}

    protected void playDemonstrationMusic(int musicIndex){}

    protected void resetPronounceTrain(){}

    protected void updateCountTime(int progress,int totalProgress){}

    protected void updateMediaPlayerProgress(){}

    protected float getSlowScore(){
        return 0;
    }

    /*************************外部调用*******************************/
    public void startSubModeTrain(){
        startTrain();
    }

    public void speechEvaluationSuccess(int grade, String url, LgEvaluateObj skegnResult){
        onSuccessSpeechEvaluation(grade,url,skegnResult);
    }

    /**
     * 恢复训练
     */
    public void resumeTrainStudy(){
        continueTrain();
    }

    /**
     * 暂停训练
     * @ isReset 是否重置样式
     */
    public void pauseTrainStudy(boolean isReset){
        pauseTimer();
        pauseCurrentSubTrain(isReset);
    }

    /**
     * 定时器暂停
     */
    public void pauseTimer(){
        pauseSecondTimer();
        pauseCountTimeTimer();
        pauseMeidaProgressTimer();
    }

    public void startRecordSpeechEvaluation(String url,String content){
        startCountTimeTimer();
        startSpeechEvaluation(content,url);
    }

    public void stopRecordSpeechEvaluation(){
        stopSpeechEvaluation(true);
    }

    public void autoScroll(RecyclerView recyclerView, int position, int totalSize, boolean forward){
        scrollIndex(recyclerView,position,totalSize,forward);
    }

    public void startDripMusic(){
        playDripSoundMusic();
    }

    /**
     * 进入发音训练结果界面
     * @param score
     * @param recordUrlList
     */
    public void enterPronounceResultActivity(int score, List<String> recordUrlList,String resultModel){
        if(getActivity() instanceof KlgBaseTrainActivity){
            ((KlgBaseTrainActivity)getActivity()).enterPronounceTrainResultActivity(score,recordUrlList,resultModel);
        }
    }

    /**
     * 是否已通过
     */
    public boolean isPass(){
        return false;
    }

    /**
     * 进入发音跟读训练下个流程
     * @param score
     * @param recordUrl
     */
    public void enterPronounceRepeatNextTrainModel(int score,String recordUrl){
        changePronounceRepeatTrainModel(score,recordUrl);
    }

    public void changePronounceTrainModel(PronounceBaseFragment.PronounceState pronounceState){
        changePronounceSubTrainModel(pronounceState);
    }

    public void startSecondCountTime(){
        startSecondTimer();
    }

    public void startNextQuesTraion(){
        startNextUsageQuesTrain();
    }

    public void usageQuesTrainResultMediaPlayer(boolean isCorrect){
        quesResultMuiscPlayer(isCorrect);
    }

    public void restartUsageTrain(){
        resetUsageTrain();
    }

    public void restartProunciatioTrain(){
        resetPronounceTrain();
    }

    public void playDemonstrationSound(int musicIndex){
        pauseTimer();
        pauseDripSoundPlay();
        stopSpeechEvaluation(false);
        playDemonstrationMusic(musicIndex);
    }

    /**
     * 更新3，2，1倒计时进度
     * @param progress
     */
    public void updateCountTimeProgress(int progress,int totalProgress){
        updateCountTime(progress,totalProgress);
    }

    /**
     * 我不练了
     */
    public void giveUpCurrentTrain(){
        giveUpTrain();
    }

    public float getSlowRepeatScore(){
        return getSlowScore();
    }

    public void restartCountTimeTrain(){
        enableStartTrain(0);
    }

    /**
     * 外部调用更新作答结果
     * @param isQuality
     */
    public void updateCurrentTrainResult(boolean isQuality,float grade){
        updateTrainResult(isQuality,grade);
    }


    /*************************定时器*************************************/

    protected void initCountTimeTimer(){
        timerTask_progress = new TimerTask() {
            @Override
            public void run() {
                recorderProgress+=20;
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        upDateRecordProgress();
                    }
                });
            }
        };
        timer_progress = new Timer();
    }

    protected void destroyCountTimeTimer(){
        if(timer_progress !=null){
            timer_progress.cancel();
            timer_progress =null;
        }
        if(timerTask_progress !=null){
            timerTask_progress.cancel();
            timerTask_progress =null;
        }
    }

    protected void startCountTimeTimer(){
        trainCountTime=TRAINRESULT_TIME;
        destroyCountTimeTimer();
        initCountTimeTimer();
        timer_progress.schedule(timerTask_progress,20,20);
    }

    protected void pauseCountTimeTimer(){
        if(timer_progress !=null){
            timer_progress.cancel();
        }
    }

    //示范音
    protected void initMeidaProgressTimer(){
        timerTask_mediaProgress = new TimerTask() {
            @Override
            public void run() {
                if(getActivity()==null){
                    return;
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        updateMediaPlayerProgress();
                    }
                });
            }
        };
        timer_mediaProgress = new Timer();
    }

    protected void destroyMeidaProgressTimer(){
        if(timer_mediaProgress !=null){
            timer_mediaProgress.cancel();
            timer_mediaProgress =null;
        }
        if(timerTask_mediaProgress !=null){
            timerTask_mediaProgress.cancel();
            timerTask_mediaProgress =null;
        }
    }

    protected void startMeidaProgressTimer(){
        destroyMeidaProgressTimer();
        initMeidaProgressTimer();
        Log.e("aaaaaa","startMeidaProgressTimer.....");
        timer_mediaProgress.schedule(timerTask_mediaProgress,0,300);
    }

    protected void pauseMeidaProgressTimer(){
        if(timer_mediaProgress !=null){
            timer_mediaProgress.cancel();
        }
    }



    protected void initSecondTimer(){
        resultCountTime=0;
        timerTask_second = new TimerTask() {
            @Override
            public void run() {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(isCountTimePause){
                            return;
                        }
                        resultCountTime+=20;
                        if(resultCountTime%1000==0){
                            secondCountTime--;
                            upDateSecondCountTime();
                        }
                        upDateResultCountTime(resultCountTime,trainCountTime);
//                        getActivity().runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//
//                            }
//                        });
                    }
                });
            }
        };
        timer_second = new Timer();
    }

    protected void destroySecondTimer(){
        if(timer_second !=null){
            timer_second.cancel();
            timer_second =null;
        }
        if(timerTask_second !=null){
            timerTask_second.cancel();
            timerTask_second =null;
        }
    }

    protected void startSecondTimer(){
        isCountTimePause=false;
        Log.e(TAG, "startSecondTimer: 开始秒计时");
        destroySecondTimer();
        initSecondTimer();
        timer_second.schedule(timerTask_second,20,20);
    }

    protected void pauseSecondTimer(){
        isCountTimePause=true;
        Log.e(TAG, "pauseSecondTimer: 暂停秒计时");
        if(timer_second !=null){
            timer_second.cancel();
        }
    }

}
